<?php
class Register extends CI_Controller
{
	
    function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $data['email_address'] = $this->input->post('email_address');
        //check email address from database
        $sql = $this->db->get_where('member', array('email' => $data['email_address']));
        if($sql->num_rows() > 0) {
        	$_data = array('status' => false, 'message' => 'Email address was already exists');	
        } else {
        	$this->load->helper('string');
        	$code_confirm = random_string('alpha', 15);
        	$this->db->insert('member', array('email' => $data['email_address'], 'code_confirm_reg' => $code_confirm, 'time_added' => time()));
        	$data['url_confirm'] = base_url(). 'register/step1/'.$code_confirm;


	        $this->loadMail();
	        $this->email->from("tinapc@gmail.com", "Complete your sign up");
	        $this->email->to($data['email_address']);
	        $this->email->subject('Complete your sign up');
	        $this->email->message($this->load->view('register/confirm_email', $data,TRUE));
	        $this->email->set_newline("\r\n");	

	        if($this->email->send()) {

	                $_data = array('status' => true ,'message' => 'We were send an email confirmation to you. Please check email to continue');
	        } else {
	                $_data = array('status' => false, 'message' => 'Send mail faild'); 
	        }	
        }
        

        echo json_encode($_data);
    }

    public function step1(){
    	$data['code_confirm'] = $this->uri->segment(3);
    	$this->load->view('register/step1', $data);
    }

    public function complete(){
    	$fullname = $this->input->post('fullname');
    	$password = md5(md5($this->input->post('password')));
    	$code_confirm = $this->input->post('code_confirm');
    	//Update to database
    	$this->db->update('member', array('fullname' => $fullname, 'password' => $password, 'status' => 1), array('code_confirm_reg' => $code_confirm));

    	//Set session as auto login after update success
    	$arr = array(
    		'loginStatus' => TRUE,
    		'sess_fullname' => $fullname,
            'log_with_fb' => FALSE
    	);
    	$this->session->set_userdata($arr);
    	echo json_encode(array());
    }

    public function update_info(){
        $fullname = $this->input->post('fullname');
        $password = md5(md5($this->input->post('password')));
        $memId = (int)$this->input->post('memId');
        //Update to database
        $this->db->update('member', array('fullname' => $fullname, 'password' => $password, 'status' => 1), array('id' => $memId));

        //Set session as auto login after update success
        $arr = array(
            'loginStatus' => TRUE,
            'sess_fullname' => $fullname,
            'sess_memId'    => $memId,
            'log_with_fb' => TRUE
        );
        $this->session->set_userdata($arr);
        echo json_encode(array());   
    }

    function loadMail()
	{
		$mail_config = array(
			'protocol'		=> 'smtp',
			'smtp_host'		=> $this->config->item('smtp_host'),
			'smtp_user'		=> $this->config->item('smtp_user'),
			'smtp_pass'		=> $this->config->item('smtp_pass'),
			'smtp_port'		=> $this->config->item('smtp_port'),
			'smtp_timeout'	=> $this->config->item('smtp_timeout'),
			'charset'		=> $this->config->item('mail_charset'),
			'wordwrap'		=> $this->config->item('mail_wordwrap'),
			'mailtype'		=> $this->config->item('mailtype')
		);

		$this->load->library('email', $mail_config);

	}

    public function upload_avatar(){
        //$this->load->library('upload');
        //$curUserName =  $_POST['curUserName'];
        $code_confirm = $_POST['code_confirm'];
        //$hh = 'tester';
        // Dir to upload  
        $uploadDir = './data_uploads/avatar/';        
        if(!is_dir($uploadDir)) {
            mkdir($uploadDir);
            chmod($uploadDir, 0777);
        }
        //$saveDirLarge = substr($uploadDir, 2).'/';

        $config['upload_path'] = $uploadDir;
        $config['allow_flash'] = TRUE;
        $config['allowed_types'] = '*';
        $config['max_size']    = '2048';
        //$config['max_width']  = '1024';
        //$config['max_height']  = '768';
        $config['encrypt_name'] = TRUE;
        $this->load->library('upload', $config);

        if (! $this->upload->do_upload('userfile')){
            echo ($this->upload->display_errors());                       
        } else {
            $dataUpload = $this->upload->data();
            $imgLarge = 'data_uploads/avatar/'. $dataUpload['file_name'];
            list($width) = getimagesize($dataUpload['full_path']);
            if($width > 140)
            {
                $this->load->library('image_lib');
                $config['image_library'] = 'GD2';
                $config['source_image'] = $dataUpload['full_path'];
                $config['quality'] = 75;
                $config['maintain_ratio'] = TRUE;
                $config['master_dim'] = 'auto';
                $config['width'] = 140;
                $config['height'] = 140;

                $this->image_lib->initialize($config);
                $this->image_lib->resize();
            }
            //$image_thumb = $saveDirThumb . $dataUpload['file_name'];
            //Kiem tra neu da co avatar roi thi xoa
            $checkFile = $this->db->select('avatar')->get_where('member', array('code_confirm_reg' => $code_confirm));
            if($checkFile->num_rows() > 0 ) {
                $result = $checkFile->row();
                if($result->avatar !== null) @unlink($result->avatar);
            }

            $arr_img = array(
                'avatar' => $imgLarge,
            );  

            //$this->db->insert('user_avatar', $arr_img);
            $this->db->update('member', $arr_img, array('code_confirm_reg' => $code_confirm));
            
            echo json_encode($this->upload->data());                   
        }  
    }
}